package Java基础.JUC同步工具.Semaphore;

import java.util.concurrent.Semaphore;

/**
 * @Title 实现一个限流器
 * <p>
 * Semaphore#acquire阻塞式方法对于高并发场景下的限流会是致命的，
 * 因为Semaphore默认使用非公平锁，高并发下竞争激烈，有些线程可能会被一直阻塞直到最后才能拿到信号量得以执行
 * <p>
 * 文章来源：https://mp.weixin.qq.com/s/D-jjCqwCsMbUuE5ZNhEKag
 */
public class ConcurrencyLimit {
    private Semaphore semaphore;

    private ConcurrencyLimit() {
    }

    public static ConcurrencyLimit create(int permits) {
        ConcurrencyLimit concurrencyLimit = new ConcurrencyLimit();
        concurrencyLimit.semaphore = new Semaphore(permits); // 默认非公平
//        concurrencyLimit.semaphore = new Semaphore(permits,true);
        return concurrencyLimit;
    }

    public void acquire() throws InterruptedException {
        this.semaphore.acquire();
    }

    public void release() {
        this.semaphore.release();
    }

    public boolean tryAcquire() {
        return this.semaphore.tryAcquire();
    }
}